﻿using System;
using Gfw.Infrastructure.ExceptionImpl;
using Gfw.Infrastructure.Facilities;
using Gfw.Infrastructure.Stock.Enums;
using Gfw.Models.Stock;
using Gfw.Repositories.Stock;
using Gfw.Repository;

namespace Gfw.Infrastructure.Stock.Facilities
{
    public class CancelTradeFacility : IFacility
    {
        private StkWaitbargainpool _agencyPool;

        public CancelTradeFacility(StkWaitbargainpool agencyPool)
        {
            _agencyPool = agencyPool;
        }

        public void Execute(Repository.UnitOfWork unitOfWork = null)
        {
            if (unitOfWork != null)
                throw new GfwTransactionInvalidException("撤单事务只能作为原子操作。");
            UnitOfWork work = new UnitOfWork();

            //更改用户股票帐户信息
            UserAccountRepository accountRep = new UserAccountRepository();
            var account = accountRep.Get(_agencyPool.UserId, work);
            if (_agencyPool.TradeType == (int)TradeTypeEnum.Buy)
            {
                //买股撤单，需要退还股票比
                account.StockMoney += _agencyPool.AgencyCount * _agencyPool.AgencyPrice;
            }
            else if (_agencyPool.TradeType == (int)TradeTypeEnum.Sell)
            {
                //卖股撤单，需要退还股票
                account.StockCount += _agencyPool.AgencyCount;
            }
            accountRep.Update(account, work);

            //执行撤单操作，删除Pool，
            _agencyPool.AgencyCount = 0;
            WaitBargainPoolRepository poolRep = new WaitBargainPoolRepository();
            poolRep.Delete(_agencyPool.Id, work);

            //修改委托状态
            BargainAgencyRepository agencyRep = new BargainAgencyRepository();
            var agency = agencyRep.Get(_agencyPool.AgencyId);
            agency.TradeStatus = (int)TradeStatusEnum.Done;
            agencyRep.Update(agency, work);

            //增加撤单的交易记录
            StkBargainrecord record = new StkBargainrecord()
            {
                Id = Guid.NewGuid().ToString(),
                ActualCount = 0,
                ActualPrice = agency.AgencyPrice,
                AgencyCount = agency.AgencyCount,
                AgencyId = agency.Id,
                AgencyPrice = agency.AgencyPrice,
                AwardSerialNo =
                    agency.TradeType == (int)TradeTypeEnum.Sell
                        ? Guid.NewGuid().ToString()
                        : "",
                BargainDate = DateTime.Now,
                BargainType = (int)TradeTypeEnum.Cancel,
                TotalPrice = 0,
                Userid = agency.Userid,
                Income = 0,
                Taxation = 0
            };

            BargainRecordRepository recordRep = new BargainRecordRepository();
            recordRep.Save(record, work);

           

            work.Commit();


        }
    }
}
